package com.ostrich.cloud.ostrichUserService.app.controller;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.isuyu.boot.oss.starter.autoconfigure.service.OssService;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.ostrich.cloud.common.result.PageResult;
import com.ostrich.cloud.common.result.Result;

import com.ostrich.cloud.ostrichUserService.app.config.JwtHelper;
import com.ostrich.cloud.ostrichUserService.app.utils.GetParentId;
import com.ostrich.cloud.ostrichUserService.client.CustomerMangerClient;
import com.ostrich.cloud.ostrichUserService.infra.model.Customer;
import com.ostrich.cloud.ostrichUserService.infra.model.UserParent;
import com.ostrich.cloud.ostrichUserService.service.CustomerService;
import com.ostrich.cloud.ostrichUserService.service.UserParentService;
import com.ostrich.ostrichUserService.dto.CustomerDto;
import com.ostrich.ostrichUserService.dto.UserParentDto;
import com.ostrich.ostrichUserService.param.CusPasswordParam;
import com.ostrich.ostrichUserService.param.LoginCusParam;
import com.ostrich.ostrichUserService.param.RegCustomerParam;
import com.ostrich.ostrichUserService.param.UpdateCusParam;
import com.woniuxy.cloud.starter.logging.Log;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.woniuxy.cloud.starter.context.ContextInfoHolder.resetContextInfo;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2022-10-26
 */
@RestController
@Slf4j
public class CustomerController implements CustomerMangerClient {


    @Resource
    private CustomerService customerService;

    @Autowired
    private OssService ossService;

    @Resource
    private JwtHelper jwtHelper;

    @Resource
    private UserParentService userParentService;

    @Override
    public Result customerRegister(RegCustomerParam regCustomerParam) {

        customerService.Register(regCustomerParam);
        return Result.ok();
    }

    @Override
    public Result uploadCusImg(MultipartFile file) throws IOException {
        String s = IdUtil.getSnowflake(2, 2).nextIdStr();
        String originalFilename = file.getOriginalFilename();
        originalFilename = s+originalFilename;

        String img = ossService.upload(originalFilename+".jpg", file.getInputStream());
        return Result.ok(img);
    }

    @Override
    @Log
    public Result updateCusMessage(UpdateCusParam updateCusParam) {
        Integer parentId = GetParentId.getParentId();
        Customer customer = BeanUtil.copyProperties(updateCusParam, Customer.class);
        customer.setParentId(parentId);
        customerService.updateCusMessage(customer);
        return Result.ok();
    }

    @Override
    public Result getCusMessage() {
        Integer parentId = GetParentId.getParentId();
        Customer customer = customerService.getOne(new QueryWrapper<Customer>().eq("parent_id", parentId));
        UserParent userParent = userParentService.getOne(new QueryWrapper<UserParent>().eq("parent_id", parentId));

        CustomerDto customerDto = BeanUtil.copyProperties(customer, CustomerDto.class);
        customerDto.setUserParent(BeanUtil.copyProperties(userParent, UserParentDto.class));
        return Result.ok(customerDto);
    }

    @Override
    public Result getAllCusMessage(Integer current,Integer size,String status) {
        PageResult<CustomerDto> allCusMessage = customerService.getAllCusMessage(current, size, status);
        return Result.ok(allCusMessage);
    }

    /**
     * 顾客登录
     * @param loginCusParam 接受参数
     * @return
     */
    @Override
    public Result customerLogin(LoginCusParam loginCusParam) {

        UserParent userParent = customerService.customerLogin(loginCusParam);
        Date date = DateUtils.addDays(new Date(), 1);
        HashMap<String, Object> map = new HashMap<>();
        map.put("operatorId",userParent.getParentId());
        map.put("operatorName","customer");
        String jwt = jwtHelper.createJWT(date, map);
        //  第一步：比对前端提交的账号名称、密码
        return Result.ok(jwt);
    }

    @Override
    public Result cusPasswordUp(CusPasswordParam cusPasswordParam) {
        Integer parentId = GetParentId.getParentId();
        cusPasswordParam.setParentId(parentId);
        customerService.updatePassword(cusPasswordParam);
        return Result.ok();
    }

    @Override
    public Result upCusStatus(Integer parentId,String status) {
        customerService.upCusStatus(parentId,status);
        return Result.ok();
    }


    public Result pay(Double price) {
        String s = IdUtil.getSnowflake(2, 2).nextIdStr();
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(URLEncoder.encode("123123", "UTF-8"), s, price+"", "");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        log.info("返回值是{}",response.getBody());
        return Result.ok(response.getBody());
    }

    @Override
    @SneakyThrows
    public Result updateMoney(BigDecimal price) {
        Integer parentId = GetParentId.getParentId();
        customerService.reduce(parentId,price);
        return Result.okm("修改余额成功");
    }

    @Override
    public Result getCustomerById(Integer customerId) {

        Customer customer = customerService.getOne(new QueryWrapper<Customer>().eq("parent_id", customerId));
        UserParent userParent = userParentService.getOne(new QueryWrapper<UserParent>().eq("parent_id", customerId));

        CustomerDto customerDto = BeanUtil.copyProperties(customer, CustomerDto.class);
        customerDto.setUserParent(BeanUtil.copyProperties(userParent, UserParentDto.class));
        return Result.ok(customerDto);
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
//                System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单未已支付
//                ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);
                customerService.pay(GetParentId.getParentId(),params.get("total_amount"));
            }
        }
        return "success";
    }
}

